package com.example.mybaiduweishi.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import com.example.mybaiduweishi.utils.MyUtil;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/6/4 0004.
 */

public class AddressDao {

    /**
     * 打开数据库，查询号码归属地
     */
    public static String queryAdress(String num , Context context){
        String location = "";
        //1、获取数据库的路径
        File file = new File(context.getFilesDir(),"mobile.db");
        /**
         * 2、打开数据库
         * getAbsolutePath : 获取文件的绝对路径
         * factory : 游标工厂
         */
        SQLiteDatabase database = SQLiteDatabase.openDatabase(file.getAbsolutePath(),
                null,SQLiteDatabase.OPEN_READONLY);
        /**
         * 3、查询号码归属地
         *  subString : 包含头不包含尾
         */
        Cursor cursor = database.rawQuery("select MobileArea from dm_mobile where MobileNumber = ?"
                , new String[]{num.substring(0,7)});
        //电信
        final String CHINA_TELECOM_PATTERN = "(^1(33|53|7[37]|8[019])\\d{8}$)|(^1700\\d{7}$)";
        //联通
        final String CHINA_UNICOM_PATTERN = "(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^170[7-9]\\d{7}$)";
        //移动
        final String CHINA_MOBILE_PATTERN = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
        final String PHONE_PATTERN=new StringBuilder(300).append(CHINA_MOBILE_PATTERN)
                .append("|")
                .append(CHINA_TELECOM_PATTERN)
                .append("|")
                .append(CHINA_UNICOM_PATTERN)
                .toString();
        if (num.matches(PHONE_PATTERN)){
            /**
             * 4、解析cursor
             *  因为每个号码对应一个号码归属地，所以查询出来是一个号码归属地数据，所以用判断即可。
             */
            if (cursor.moveToNext()){
                location = cursor.getString(0);
            }
//            5、关闭数据库
            cursor.close();
        }else {
            Toast.makeText(context, "号码不符合规则", Toast.LENGTH_SHORT).show();
        }
        database.close();
        return location;
    }


}
